<template>
  <div class="uni-scroll app-container" style="height: calc(100vh - 100px)">
    <el-autocomplete
      v-model="protocol"
      class="inline-input"
      :fetch-suggestions="queryProtocolSearch"
    />
    <el-button type="primary" @click="changeData">{{ $t('confirm') }}</el-button>
    <el-row :gutter="5" style="margin-top:15px">
      <el-col :span="12">
        <el-input
          v-model="originalData"
          type="textarea"
          :rows="17"
          :placeholder="$t('ram')"
        />
      </el-col>

      <el-col :span="12">
        <span>{{ $t('protocol') }}</span>
        <json-editor v-model="protocolData"/>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import JsonEditor from '@/components/JsonEditor'
import { codecTest, listCodec } from '@/api/iot/iotCodecApi'

export default {
  name: 'Codec',
  components: {
    JsonEditor
  },
  data() {
    return {
      protocol: null,
      originalData: null,
      protocolList: [],
      protocolData: {}
    }
  },
  created() {
    this.listCodec()
  },
  methods: {
    queryProtocolSearch(queryString, cb) {
      const protocolList = this.protocolList
      const results = queryString ? protocolList.filter(this.createProtocolFilter(queryString)) : protocolList
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createProtocolFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    listCodec() {
      listCodec().then(res => {
        const { code, data } = res
        const protocolList = []
        if (code === '200') {
          data.forEach(item => {
            this.protocol = item
            protocolList.push({
              label: item,
              value: item
            })
          })
        }
        this.protocolList = protocolList
      })
    },
    changeData() {
      codecTest({
        protocol: this.protocol,
        msg: this.originalData
      }).then(res => {
        const { data, code } = res
        if (code === '200') {
          this.protocolData = data
        }
      })
    }
  }
}
</script>

